/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wephone.Student.huanxin.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatDB;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContact;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.R;
import com.wephone.Student.bean.GroupMessageResponse;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.GroupInvite;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.adapter.ChatHistoryAdapter;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.ui.BaseActivity;
import com.wephone.Student.ui.MainTabBar;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.util.Constants;

/**
 * 聊天记录Fragment
 * 
 */
public class ChatHistoryActivity extends BaseActivity {
	private InputMethodManager inputMethodManager;
	private ListView listView;
	private Map<String, User> contactList;
	private ChatHistoryAdapter adapter;
	private EditText query;
	private ImageButton clearSearch;
	public RelativeLayout errorItem;
	public TextView errorText;
//	private boolean hidden;
	private List<UserInfoData> userInfoList;
	private List<GroupInfo> groupInfoList;
	public static boolean needRefresh = false;
	private List<GroupInvite> invites= new ArrayList<GroupInvite>();
	private List<GroupInvite> inviteds= new ArrayList<GroupInvite>();
	private Boolean isFirst;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_conversation_history);
		isFirst = true;
		init();
	}

	private void init(){
		inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		errorItem = (RelativeLayout)findViewById(R.id.rl_error_item);
		errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);
		// contact list
		contactList = BaseApplication.getInstance().getContactList();
		listView = (ListView)findViewById(R.id.list);
//		adapter = new ChatHistoryAdapter(getApplicationContext(), 1, loadUsersWithRecentChat());
		// 设置adapter
//		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				EMContact emContact = adapter.getItem(position);
				if (adapter.getItem(position).getUsername().equals(BaseApplication.getInstance().getUserName()))
					Toast.makeText(getApplicationContext(), "不能和自己聊天", 0).show();
				else if(Constant.NEW_FRIENDS_USERNAME.equals(emContact.getUsername())){
					// 进入申请与通知页面
					User user = BaseApplication.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
					//user.setUnreadMsgCount(0);
					Bundle bundle = new Bundle();
					if(invites.size()==0&&inviteds.size()>0){
						bundle.putInt("type", 2);
					}else{
						bundle.putInt("type", 1);
					}
					startActivity(new Intent(getApplicationContext(), NewFriendsMsgActivity.class).putExtras(bundle));
				}else{
					// 进入聊天页面
					  Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
					 if (emContact instanceof EMGroup) {
		                    //it is group chat
		                    intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
		                    intent.putExtra("groupId", ((EMGroup) emContact).getGroupId());
		                } else {
		                    //it is single chat
		                	String userId = emContact.getUsername();
//		                	if(userId.equals("admin")){
//		                		userId = "5519";
//		                	}
		                    intent.putExtra("userId", userId);
		                    if(userId.equals("admin")){
		                    	userId = "5519";
		                    }
		                    for(UserInfoData userInfo:userInfoList){
		                    	if(userInfo.getuId().equals(userId)){
		                    		ChatActivity.toUserInfo = userInfo;
		                    		break;
		                    	}
		                    }
		                } 
					startActivity(intent);
					needRefresh = true;
				}
			}
		});
		// 注册上下文菜单
		registerForContextMenu(listView);

		listView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// 隐藏软键盘
				if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
					if (getCurrentFocus() != null)
						inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				}
				return false;
			}
		});
		// 搜索框
		query = (EditText)findViewById(R.id.query);
		// 搜索框中清除button
		clearSearch = (ImageButton)findViewById(R.id.search_clear);
		query.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				adapter.getFilter().filter(s);
				if (s.length() > 0) {
					clearSearch.setVisibility(View.VISIBLE);
				} else {
					clearSearch.setVisibility(View.INVISIBLE);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		clearSearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				query.getText().clear();
			}
		});
		
		refresh();
	}
	
//	@Override
//	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//		return inflater.inflate(R.layout.fragment_conversation_history, container, false);
//	}

//	@Override
//	public void onActivityCreated(Bundle savedInstanceState) {
//		super.onActivityCreated(savedInstanceState);
//		
//
//	}

//	@Override
//	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//		super.onCreateContextMenu(menu, v, menuInfo);
//		// if(((AdapterContextMenuInfo)menuInfo).position > 0){ m,
//		getActivity().getMenuInflater().inflate(R.menu.delete_message, menu);
//		// }
//	}

//	@Override
//	public boolean onContextItemSelected(MenuItem item) {
//		if (item.getItemId() == R.id.delete_message) {
//			EMContact tobeDeleteUser = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
//			// 删除此会话
//			EMChatManager.getInstance().deleteConversation(tobeDeleteUser.getUsername());
//			InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getApplicationContext());
//			inviteMessgeDao.deleteMessage(tobeDeleteUser.getUsername());
//			adapter.remove(tobeDeleteUser);
//			adapter.notifyDataSetChanged();
//
//			// 更新消息未读数
////			((MainActivity) getActivity()).updateUnreadLabel();
//
//			return true;
//		}
//		return super.onContextItemSelected(item);
//	}
	public void refresh2()
	{
		updateInviteMessage();
		updateInvitedMessage();
	}
	/**
	 * 刷新页面
	 */
	public void refresh() {
		System.out.println("------refresh------");
		
		Gson gson = new Gson();
		userInfoList = new ArrayList<UserInfoData>();
		String pushUserStr = ShareReferenceUtil.getPushUserInfoJson(getApplicationContext());
		if(!TextUtils.isEmpty(pushUserStr)){
			userInfoList = gson.fromJson(pushUserStr, new TypeToken<List<UserInfoData>>(){}.getType());
			System.out.println("---userInfoList.size()---"+userInfoList.size());
			
		}
		
		List<User> userList = new ArrayList<User>();
		List<String> userNameList = EMChatDB.getInstance().findAllParticipantsWithMsg();
//		System.out.println("---userNameList.size()---"+userNameList.size());
//		System.out.println("---userInfoList.size()---"+userInfoList.size());
		for(String userName:userNameList){
//			System.out.println("=====userName====="+userName);
			for(UserInfoData userInfo:userInfoList){
//				System.out.println("=====userInfo====="+userInfo.getuId());
				if(userInfo.getuId().equals(userName) || (userName.equals("admin")&&userInfo.getuId().equals("5519"))){
					User newFriends = new User();
					newFriends.setUsername(userName);
					newFriends.setNick(userInfo.getuName());
					newFriends.setHeader("");
//					userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
					userList.add(newFriends);
					break;
				}
			}
		}
		groupInfoList = new ArrayList<GroupInfo>();
		String pushGroupStr = ShareReferenceUtil.getPushGroupInfoJson(getApplicationContext());
		if(!TextUtils.isEmpty(pushGroupStr)){
			groupInfoList = gson.fromJson(pushGroupStr, new TypeToken<List<GroupInfo>>(){}.getType());
			System.out.println("---groupInfoList.size()---"+groupInfoList.size());
			
		}
		adapter = new ChatHistoryAdapter(userInfoList,groupInfoList,getApplicationContext(), R.layout.row_chat_history, loadUsersWithRecentChat(userList));
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 获取有聊天记录的users和groups
	 * 
	 * @param context
	 * @return
	 */
	private List<EMContact> loadUsersWithRecentChat(List<User> userlist) {
		List<EMContact> resultList = new ArrayList<EMContact>();
		for (User user:userlist) {
			EMConversation conversation = EMChatManager.getInstance().getConversation(user.getUsername());
			if (conversation.getMsgCount() > 0) {
				resultList.add(user);
			}
		}
		for(EMGroup group : EMGroupManager.getInstance().getAllGroups()){
			EMConversation conversation = EMChatManager.getInstance().getConversation(group.getGroupId());
			if(conversation.getMsgCount() > 0){
				resultList.add(group);
			}
			
		}
		
		// 排序
		sortUserByLastChatTime(resultList);
		List<GroupInvite> invites = this.invites;
		List<GroupInvite> inviteds = this.inviteds;
		
		if(isFirst){
		   invites = MainTabBar.s_instance.invites;
		   inviteds = MainTabBar.s_instance.inviteds;
			isFirst = false;
		}else{
		    invites = this.invites;
		    inviteds = this.inviteds;
		}
		
		if((invites.size()+inviteds.size())>0){
			User user = new User();
			user.setNick("系统通知");
			user.setUsername(Constant.NEW_FRIENDS_USERNAME);
			user.setUnreadMsgCount(invites.size()+inviteds.size());
			resultList.add(0, user);
		}
		
		//updateInviteMessage();
		return resultList;
	}
	
	 private void updateInviteMessage(){
		 RequestParams params = new RequestParams();
		 params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
		 HttpClient.getInstance().get(Constants.API_GET_CHART_MESSAGE, params, new MyResponseHandler(ChatHistoryActivity.this, GroupMessageResponse.class){
			 @Override
				public void onSuccess(String result) {
					super.onSuccess(result);
					
					if(getDataSuccess){
						GroupMessageResponse res = (GroupMessageResponse)response;
						List<GroupInvite> invites1 = res.getData();
						// System.out.println("-----unread count-----"+count);
						invites = invites1;
						//updateInviteMessage();
						
					}else{
						invites.clear();
					}
					refresh();
			 }
		 });
	 }
	 
	 private void updateInvitedMessage(){
		 RequestParams params = new RequestParams();
		 params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
		 HttpClient.getInstance().get(Constants.API_GET_CHART_INVITE, params, new MyResponseHandler(ChatHistoryActivity.this, GroupMessageResponse.class){
			 @Override
				public void onSuccess(String result) {
					super.onSuccess(result);
					
					if(getDataSuccess){
						GroupMessageResponse res = (GroupMessageResponse)response;
						List<GroupInvite> invites1 = res.getData();
						// System.out.println("-----unread count-----"+count);
						inviteds = invites1;
						//updateInviteMessage();
						
					}else{
						inviteds.clear();
					}
					refresh();
			 }
		 });
	 }
	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortUserByLastChatTime(List<EMContact> contactList) {
		Collections.sort(contactList, new Comparator<EMContact>() {
			@Override
			public int compare(final EMContact user1, final EMContact user2) {
				EMConversation conversation1 = EMChatManager.getInstance().getConversation(user1.getUsername());
				EMConversation conversation2 = EMChatManager.getInstance().getConversation(user2.getUsername());

				EMMessage user2LastMessage = conversation2.getLastMessage();
				EMMessage user1LastMessage = conversation1.getLastMessage();
				if (user2LastMessage.getMsgTime() == user1LastMessage.getMsgTime()) {
					return 0;
				} else if (user2LastMessage.getMsgTime() > user1LastMessage.getMsgTime()) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}

//	@Override
//	public void onHiddenChanged(boolean hidden) {
//		super.onHiddenChanged(hidden);
//		this.hidden = hidden;
//		if (!hidden) {
//			refresh();
//		}
//	}

	@Override
	public void onResume() {
		super.onResume();
//		if (!hidden) {
		EMChatManager.getInstance().activityResumed();
		if(needRefresh || EMChatManager.getInstance().getUnreadMsgsCount()>0){
			needRefresh = false;
			
			refresh2();
		}
//		}
	}
	
	private static long backClickTime = -1;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			 long nowTime = System.currentTimeMillis();
				if(backClickTime<=0 || nowTime-backClickTime>2000){
					backClickTime = nowTime;
					Toast.makeText(getApplicationContext(), "再按一次 退出程序", Toast.LENGTH_SHORT).show();
				}else{
					finish();
				}
          return true; 
        }
        return super.onKeyDown(keyCode, event); 
	}
	
}
